<?php

namespace apiend\modules\passport\models;

use Yii;
use common\base\Model;
use apiend\models\User;
use apiend\models\forms\SmsCaptchaForm;

/**
 * 忘记密码
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class PasswordForgetForm extends Model {

    /**
     * @var string 密码重置token
     */
    public $reset_token;

    /**
     * @var string 短信验证码
     */
    public $code;

    /**
     * @var string 待设置的新密码
     */
    public $password;

    /**
     * @var User 用户信息
     */
    private $_user = null;

    /**
     * @var string 存储的短信验证码
     */
    private $_captcha = null;

    const PASSWORD_PATTERN = '/((?=.*[a-z])(?=.*\d)|(?=[a-z])(?=.*[#@!~%^&*])|(?=.*\d)(?=.*[#@!~%^&*]))[a-z\d#@!~%^&*]{8,16}/i';

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['reset_token', 'code', 'password'], 'required'],
//            [['password'], 'match', 'pattern' => self::PASSWORD_PATTERN, 'message' => '密码过于简单'],
            ['password', 'string', 'min' => 6, 'max' => 16],
            ['reset_token', 'validateResetToken'],
            ['code', 'validateCaptcha'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateResetToken($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        if (!User::isPasswordResetTokenValid($this->$attribute)) {
            $this->addError($attribute, '校验信息已过期或者请求超时');
        } else {
            $user = $this->getUser();
            if (!$user) {
                $this->addError($attribute, '您的找回信息已过期请返回上一步重新提交');
            } elseif (!$user->meta) {
                $this->addError($attribute, '帐号信息异常，请使用其他方式找回密码');
            } else {
                $mobile = $user->meta->decryptMobile(false);
                $code = Yii::$app->cache->get('captcha_' . SmsCaptchaForm::SCOPE_FORGET . '_' . $mobile);
                $this->setCaptcha($code);
            }
        }
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptcha($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $captcha = $this->_captcha;
        if ($captcha == false) {
            $this->addError($attribute, $this->getAttributeLabel($attribute) . '已过期');
        } elseif ($captcha !== $this->$attribute) {
            $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确');
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByPasswordResetToken($this->reset_token);
        }
        return $this->_user;
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function setCaptcha($code) {
        $this->_captcha = $code;
    }

    /**
     * Sends an email with a link, for resetting the password.
     *
     * @return bool whether the email was send
     */
    public function send() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        $user = $this->getUser();
        if (!$user) {
            return false;
        }
        $user->setPassword($this->password);
        $user->removePasswordResetToken();
        return $user->save();
    }

}
